#coding=utf-8
import threading

from stockdb.misc import *
import sdsource.web.sina as sina

def fqrs2db(code):
    s = find_stock(code)
    
    if s.fqrs: return
    
    ipo = s.ipo.isoformat()
    
    f = sina.get_fqrs(code, ipo)
    
    for r in f.fqrs:
        fq = FuQuanRatio()    
        fq.stock = s
        fq.date = r[0]
        fq.ratio = r[1]
        
        sess.save(fq)
        sess.commit()

class Fqr2DB_Thread(threading.Thread):
    def __init__(self, id_, codes):
        threading.Thread.__init__(self)
        
        self.id = id_
        self.codes = codes
        
    def run(self):
        print  "线程%i启动."%self.id
        
        for c in self.codes:
            fqrs2db(c)
            
        print  "线程%i结束."%self.id    
        
if __name__ == "__main__":
    
    thread_num = 10
    
    codes = get_stcodes()
    step = len(codes)/thread_num + 1
    
    for i in range(thread_num):
    
        cs = codes[i*step: (i+1)*step]
        ft = Fqr2DB_Thread(i, cs)
        ft.start()
    
    print "主线程退出."        
